var express = require('express');
var router = express.Router();
const jwt = require("jsonwebtoken");
const UserModel = require("../../models/UserModel");
const { secret } = require("../../config/config");

router.post('/login', function(req, res, next) {
    const { username, password } = req.body;

    UserModel.findOne({ username, password }).then(user => {
        if (user) {
            // 登录成功
            let token = jwt.sign({
                username,
                password
            }, secret, {
                expiresIn: 60 * 60 * 24 * 7
            });
            return res.json({
                code: "0000",
                msg: "登录成功",
                data: { token }
            });
        } else {
            // 登录失败
            return res.status(401).json({
                code: "2001",
                msg: "用户名或密码错误",
                data: {}
            });
        }
    }).catch(err => {
        console.error(err); // 打印错误信息
        return res.status(500).json({
            code: "2002",
            msg: "服务器内部错误",
            data: {}
        });
    });
});

// 退出登录
router.post("/logout", function(req, res) {
    req.session.destroy(function(err) {
        if (err) {
            return res.status(500).json({ msg: "退出失败" });
        }
        return res.render("success", { msg: "退出成功", url: "/login" });
    });
});

module.exports = router;
